package com.yenlien.traceyun.breed.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.yenlien.traceyun.breed.dao.FeedDao;
import com.yenlien.traceyun.breed.entity.Feed;

@Service
public class FeedService {
    @Autowired
    private FeedDao feedDao;

    public Page<Feed> findByList(final Feed feed) {
        Pageable pageable = PageRequest.of(feed.getPage(), feed.getPageSize(), Sort.Direction.DESC, ("createtime"));
        return feedDao.findAll(new Specification<Feed>() {
            private static final long serialVersionUID = -1396496630802017658L;

            @Override
            public Predicate toPredicate(Root<Feed> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> inputsName = root.get("inputsName");
                Path<String> inputsBatch = root.get("inputsBatch");
                Path<String> principalName = root.get("principalName");
                Path<String> breedId = root.get("breedId");
                //构造查询条件
                List<Predicate> list = new ArrayList<Predicate>();
                if (!StringUtils.isEmpty(feed.getBreedId())) {
                    list.add(cb.equal(breedId, feed.getBreedId()));
                }
                Predicate[] predicateA = new Predicate[list.size()];
                Predicate predicateAnd = cb.and(list.toArray(predicateA));

                if (StringUtils.isNotEmpty(feed.getInputsName())) {
                    List<Predicate> list2 = new ArrayList<>();
                    list2.add(cb.like(inputsName, "%" + feed.getInputsName() + "%"));
                    list2.add(cb.like(inputsBatch, "%" + feed.getInputsBatch() + "%"));
                    list2.add(cb.like(principalName, "%" + feed.getInputsName() + "%"));
                    Predicate[] predicateO = new Predicate[list2.size()];
                    Predicate predicateOr = cb.or(list2.toArray(predicateO));
                    return query.where(predicateAnd, predicateOr).getRestriction();
                } else {
                    return predicateAnd;
                }
            }
        }, pageable);
    }

    public void save(Feed feed) {
        feed.setLastStep(feed.getBreedId());
        feedDao.save(feed);
    }
}
